package admission.ecnu.service;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import admission.ecnu.dao.classInfoDao;
import admission.ecnu.interfaces.IRnsService;
import admission.ecnu.mainservlet.RnsContext;
import admission.ecnu.object.DataManager;
import admission.ecnu.object.OClassInfo;
import admission.ecnu.object.OTeacherInfo;

public class updateClassInfo implements IRnsService {

	@Override
	public void executeService(RnsContext context) throws Exception {

		JSONObject obj = context.getJsonRequestObject();
		if (!DataManager.USER_ID.equals(obj.get("key"))) {
			JSONObject jsonReturn = new JSONObject();
			jsonReturn.put("returnCode", DataManager.RETURN_WRONGKEY);
			context.setJsonResponseObject(jsonReturn);
			return;
		}

		JSONArray objArray = obj.getJSONArray("classInfo");

		String[] classStrArray = obj.getString("classInfo").split("$");
		ArrayList<OClassInfo> classList = new ArrayList<OClassInfo>();

		for (int i = 0; i < classStrArray.length; i++) {
			OClassInfo newClass = new OClassInfo();
			String[] item = classStrArray[i].split(",");
			for (int j = 0; j < item.length; j++) {
				String[] keyValue = item[j].split("=");
				if (keyValue[0].equals("classId"))
					newClass.setClassId(keyValue[1]);
				if (keyValue[0].equals("grade"))
					newClass.setGrade(keyValue[1]);
				if (keyValue[0].equals("curriculum"))
					newClass.setCurriculum(keyValue[1]);
				if (keyValue[0].equals("type"))
					newClass.setType(keyValue[1]);
				if (keyValue[0].equals("teacher"))
					newClass.setTeacher(keyValue[1]);
				if (keyValue[0].equals("classTime"))
					newClass.setClassTime(keyValue[1]);
				if (keyValue[0].equals("classroom"))
					newClass.setClassroom(keyValue[1]);
				if (keyValue[0].equals("isExam"))
					newClass.setIsExam(keyValue[1]);
			}
			classList.add(newClass);
			System.out.print("update class" + i + ": " + classList.toString());

			newClass = null;
		}

		new classInfoDao().classUpdate(classList);

		JSONObject jsonReturn = new JSONObject();
		jsonReturn.put("returnCode", DataManager.RETURN_SUCCESSFUL);
		context.setJsonResponseObject(jsonReturn);
	}
}